package com.dianban.utils;

import org.springframework.util.StringUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * HTTPS调用工具
 * @version 1.0.0
 */
public class HttpsUtil {

    public static String callHttps(String postData, String postUrl) {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    ///////////////////////////////////////////////////华丽的分割线/////////////////////////////////////////////////////////////////
    public static String urlCall(String urlStr, String method, String param, String type){
        return urlCall(urlStr,"utf-8", method, param, type);
    }

    public static String urlCall(String urlStr, String code, String method, String jsonStrParam, String type) {
        System.out.println(",请求连接地址：" + urlStr);
        code = StringUtils.isEmpty(code) ? "utf-8" : code;
        method = StringUtils.isEmpty(method)? "POST" : method;
        StringBuffer document = new StringBuffer();
        try {
            HttpURLConnection conn = null;
            URL url = new URL(urlStr);
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                            + session.getPeerHost());
                    return true;
                }
            };
            try {
                trustAllHttpsCertificates();
            } catch (Exception e) {
                e.printStackTrace();
            }

            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            conn = (HttpURLConnection) url.openConnection();
            //conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("Charset", "UTF-8");
            //conn.setRequestProperty("Content-Type", code);
            conn.setRequestMethod(method);

            conn.setDoInput(true);
            conn.setDoOutput(true);
            if(method.equals("POST")){
                // 传参
                conn.setRequestProperty("Content-Length",
                        String.valueOf(jsonStrParam.getBytes().length));
                conn.setUseCaches(false);
                //设置为gbk可以解决服务器接收时读取的数据中文乱码问题
                conn.getOutputStream().write(jsonStrParam.getBytes("UTF-8"));
                conn.getOutputStream().flush();
                conn.getOutputStream().close();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), code));
            String line = null;
            while ((line = reader.readLine()) != null)
                document.append(line + "\n");
            reader.close();
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String str = document.toString();
        return str;
    }

    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                .getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc
                .getSocketFactory());
    }

    static class miTM implements javax.net.ssl.TrustManager,
            javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

}
